package com.coursehub.course.controller;

import com.coursehub.course.dto.CourseCreateDto;
import com.coursehub.course.dto.CourseUpdateDto;
import com.coursehub.course.entity.Course;

import com.coursehub.course.service.CourseService;
import com.coursehub.coursemanagement.service.EnrollmentTransactionService;
import com.coursehub.shared.dto.ApiResponse;
import com.coursehub.shared.transaction.TransactionResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import java.util.List;

/**
 * 课程管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/courses")
@RequiredArgsConstructor
@Validated
public class CourseController {
    
    private final CourseService courseService;
    private final EnrollmentTransactionService enrollmentTransactionService;
    
    /**
     * 创建课程
     */
    @PostMapping
    public ResponseEntity<ApiResponse<Course>> createCourse(@Valid @RequestBody CourseCreateDto createDto) {
        log.info("创建课程请求: {}", createDto.getCourseName());
        
        // 从认证上下文中获取用户ID
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.getDetails() != null) {
            // 从认证详情中获取用户ID（由JWT过滤器设置）
            String userId = (String) authentication.getDetails();
            createDto.setUserId(userId);
        }
        
        Course course = courseService.createCourse(createDto);
        return ResponseEntity.status(HttpStatus.CREATED)
                .body(ApiResponse.success(course, "课程创建成功"));
    }
    
    /**
     * 兼容原有接口：创建课程（支持原有的payload格式）
     */
    @PostMapping("/createCourse")
    public ResponseEntity<Course> createCourseCompatible(@RequestBody CourseCreateDto createDto) {
        log.info("创建课程请求(兼容接口): {}", createDto.getCourseName());
        Course course = courseService.createCourse(createDto);
        return ResponseEntity.status(HttpStatus.CREATED).body(course);
    }
    
    /**
     * 根据ID获取课程
     */
    @GetMapping("/{courseId}")
    public ResponseEntity<ApiResponse<Course>> getCourseById(
            @PathVariable @NotBlank(message = "课程ID不能为空") String courseId) {
        Course course = courseService.getCourseById(courseId);
        return ResponseEntity.ok(ApiResponse.success(course));
    }
    
    /**
     * 获取所有课程
     */
    @GetMapping
    public ResponseEntity<ApiResponse<List<Course>>> getAllCourses() {
        List<Course> courses = courseService.getAllCourses();
        return ResponseEntity.ok(ApiResponse.success(courses));
    }
    
    /**
     * 更新课程信息
     */
    @PutMapping("/{courseId}")
    public ResponseEntity<ApiResponse<Course>> updateCourse(
            @PathVariable @NotBlank(message = "课程ID不能为空") String courseId,
            @Valid @RequestBody CourseUpdateDto updateDto) {
        log.info("更新课程请求: {}", courseId);
        Course course = courseService.updateCourse(courseId, updateDto);
        return ResponseEntity.ok(ApiResponse.success(course, "课程更新成功"));
    }
    
    /**
     * 删除课程
     */
    @DeleteMapping("/{courseId}")
    public ResponseEntity<ApiResponse<Void>> deleteCourse(
            @PathVariable @NotBlank(message = "课程ID不能为空") String courseId) {
        log.info("删除课程请求: {}", courseId);
        courseService.deleteCourse(courseId);
        return ResponseEntity.ok(ApiResponse.success("课程删除成功"));
    }
    
    /**
     * 根据课程名称搜索课程
     */
    @GetMapping("/search")
    public ResponseEntity<ApiResponse<List<Course>>> searchCourses(
            @RequestParam(required = false) String courseName,
            @RequestParam(required = false) String examinationMethod) {
        List<Course> courses;
        
        if (courseName != null && examinationMethod != null) {
            courses = courseService.searchCourses(courseName, examinationMethod);
        } else if (courseName != null) {
            courses = courseService.searchCoursesByName(courseName);
        } else if (examinationMethod != null) {
            courses = courseService.getCoursesByExaminationMethod(examinationMethod);
        } else {
            courses = courseService.getAllCourses();
        }
        
        return ResponseEntity.ok(ApiResponse.success(courses));
    }
    
    /**
     * 检查课程是否存在
     */
    @GetMapping("/{courseId}/exists")
    public ResponseEntity<ApiResponse<Boolean>> checkCourseExists(
            @PathVariable @NotBlank(message = "课程ID不能为空") String courseId) {
        boolean exists = courseService.existsByCourseId(courseId);
        return ResponseEntity.ok(ApiResponse.success(exists));
    }
    
    /**
     * 检查课程名称是否存在
     */
    @GetMapping("/name/{courseName}/exists")
    public ResponseEntity<ApiResponse<Boolean>> checkCourseNameExists(
            @PathVariable @NotBlank(message = "课程名称不能为空") String courseName) {
        boolean exists = courseService.existsByCourseName(courseName);
        return ResponseEntity.ok(ApiResponse.success(exists));
    }
    
    /**
     * 验证用户对课程的权限
     */
    @GetMapping("/{courseId}/users/{userId}/permission")
    public ResponseEntity<ApiResponse<Boolean>> validateUserPermission(
            @PathVariable @NotBlank(message = "课程ID不能为空") String courseId,
            @PathVariable @NotBlank(message = "用户ID不能为空") String userId) {
        boolean hasPermission = courseService.validateUserPermission(userId, courseId);
        return ResponseEntity.ok(ApiResponse.success(hasPermission));
    }
    
    // ====================== 课程教师管理API ======================
    
    /**
     * 获取指定课程的所有教师
     */
    @GetMapping("/{courseId}/teachers")
    public ResponseEntity<ApiResponse<List<String>>> getTeachersInCourse(
            @PathVariable @NotBlank(message = "课程ID不能为空") String courseId) {
        log.info("获取课程教师列表: {}", courseId);
        List<String> teachers = courseService.getTeachersInCourse(courseId);
        return ResponseEntity.ok(ApiResponse.success(teachers));
    }
    
    /**
     * 获取指定课程的所有学生
     */
    @GetMapping("/{courseId}/students")
    public ResponseEntity<ApiResponse<List<String>>> getStudentsInCourse(
            @PathVariable @NotBlank(message = "课程ID不能为空") String courseId) {
        log.info("获取课程学生列表: {}", courseId);
        List<String> students = courseService.getStudentsInCourse(courseId);
        return ResponseEntity.ok(ApiResponse.success(students));
    }
    
    /**
     * 将教师添加到指定课程
     */
    @PostMapping("/{courseId}/teachers/{userId}")
    public ResponseEntity<ApiResponse<Void>> addTeacherToCourse(
            @PathVariable @NotBlank(message = "课程ID不能为空") String courseId,
            @PathVariable @NotBlank(message = "用户ID不能为空") String userId) {
        log.info("添加教师到课程: courseId={}, userId={}", courseId, userId);
        courseService.addTeacherToCourse(courseId, userId);
        return ResponseEntity.ok(ApiResponse.success("教师添加成功"));
    }
    
    /**
     * 从指定课程中移除教师
     */
    @DeleteMapping("/{courseId}/teachers/{userId}")
    public ResponseEntity<ApiResponse<Void>> removeTeacherFromCourse(
            @PathVariable @NotBlank(message = "课程ID不能为空") String courseId,
            @PathVariable @NotBlank(message = "用户ID不能为空") String userId) {
        log.info("从课程中移除教师: courseId={}, userId={}", courseId, userId);
        courseService.removeTeacherFromCourse(courseId, userId);
        return ResponseEntity.ok(ApiResponse.success("教师移除成功"));
    }
    
    /**
     * 根据用户ID和角色获取课程列表
     */
    @GetMapping("/users/{userId}/role/{role}")
    public ResponseEntity<ApiResponse<List<Course>>> getCoursesByUserIdAndRole(
            @PathVariable @NotBlank(message = "用户ID不能为空") String userId,
            @PathVariable @NotBlank(message = "角色不能为空") String role) {
        log.info("根据用户ID和角色获取课程列表: userId={}, role={}", userId, role);
        List<Course> courses = courseService.getCoursesByUserIdAndRole(userId, role);
        return ResponseEntity.ok(ApiResponse.success(courses));
    }
    
    // ====================== 统计分析相关API ======================
    
    /**
     * 验证学生是否选修了该课程
     */
    @GetMapping("/{courseId}/students/{studentId}/enrolled")
    public ResponseEntity<ApiResponse<Boolean>> checkStudentEnrolled(
            @PathVariable @NotBlank(message = "课程ID不能为空") String courseId,
            @PathVariable @NotBlank(message = "学生ID不能为空") String studentId) {
        log.info("验证学生选课状态: courseId={}, studentId={}", courseId, studentId);
        boolean enrolled = courseService.isStudentEnrolledInCourse(courseId, studentId);
        return ResponseEntity.ok(ApiResponse.success(enrolled));
    }
    
    /**
     * 学生选课（使用分布式事务）
     */
    @PostMapping("/{courseId}/students/{studentId}/enroll")
    public ResponseEntity<ApiResponse<String>> enrollStudent(
            @PathVariable @NotBlank(message = "课程ID不能为空") String courseId,
            @PathVariable @NotBlank(message = "学生ID不能为空") String studentId) {
        log.info("学生选课请求: courseId={}, studentId={}", courseId, studentId);
        
        try {
            // 使用分布式事务处理学生选课，同步等待结果
            TransactionResult result = enrollmentTransactionService.enrollStudent(studentId, courseId).get();
            
            if (result.isSuccess()) {
                log.info("学生选课成功: courseId={}, studentId={}", courseId, studentId);
                return ResponseEntity.ok(new ApiResponse<>(200, "Success", "选课成功", System.currentTimeMillis()));
            } else {
                log.error("学生选课失败: courseId={}, studentId={}, 错误: {}", 
                        courseId, studentId, result.getErrorMessage());
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(ApiResponse.error("选课失败: " + result.getErrorMessage()));
            }
            
        } catch (Exception e) {
            log.error("学生选课失败: courseId={}, studentId={}", courseId, studentId, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.error("选课失败: " + e.getMessage()));
        }
    }
}